from db import get_db


def get_share():
    db = get_db()
    data = db.execute(
        "SELECT * FROM share ORDER BY create_time desc "
    ).fetchall()
    return data


def get_share_by_id(share_id):
    db = get_db()
    data = db.execute(
        "SELECT * FROM share WHERE share_id = ? ",
        (share_id,)
    ).fetchone()
    return data


def create_share(share_id, share_pwd, share_name, folder):
    db = get_db()
    db.execute(
        'INSERT INTO share (share_id, share_pwd, share_name, folder)'
        ' VALUES (?, ?, ?,?)',
        (share_id, share_pwd, share_name, folder)
    )
    db.commit()


def delete_share(share_id):
    db = get_db()
    db.execute('DELETE FROM share WHERE share_id = ?', (share_id,))
    db.commit()


def save_file(data):
    db = get_db()
    db.execute(
        'INSERT INTO file (share_id,parent_file_id,file_id,type,name)'
        ' VALUES (?,?,?, ?,?)',
        (data['share_id'], data['parent_file_id'], data['file_id'], data['type'], data['name'])
    )
    db.commit()


def update_file(file_id, download_status):
    db = get_db()
    db.execute(
        'UPDATE file SET download_status = ? where file_id = ?',
        (download_status, file_id)
    )
    db.commit()


def update_file_alias(file_id, alias):
    db = get_db()
    db.execute(
        'UPDATE file SET alias = ? where file_id = ?',
        (alias, file_id)
    )
    db.commit()


def get_file(share_id, parent_file_id):
    db = get_db()
    data = db.execute(
        "SELECT * FROM file WHERE share_id =  ? AND parent_file_id = ? ORDER BY id desc ",
        (share_id, parent_file_id)
    ).fetchall()
    return data


def get_file_path(share_id, file_id):
    db = get_db()
    data = db.execute(
        'SELECT s.folder, ifnull(f2.alias,f2.name) as alias, f.name FROM file f '
        'LEFT JOIN file f2 on f2.file_id = f.parent_file_id '
        'LEFT JOIN share s on s.share_id = f.share_id '
        'WHERE f.share_id = ? and f.file_id = ?',
        (share_id, file_id)
    ).fetchone()
    return data


def delete_file(share_id, file_id):
    db = get_db()
    db.execute('DELETE FROM file WHERE share_id = ? AND file_id = ?', (share_id, file_id))
    db.commit()
